﻿using System;

namespace JQuery.WebKit.Common.Utilities
{
    public class GenericConverter
    {
        public static T Parse<T>(object value)
        {
            try
            {
                Type type = typeof(T);

                if (type.Name == "Nullable`1")
                {
                    type = Nullable.GetUnderlyingType(type);
                }

                if (type.BaseType.Name == "Enum")
                {
                    return (T)Enum.Parse(type, value.ToString().Replace(" ", ""));
                }

                if (type.Name == "Guid")
                {
                    return (T)(object)(new Guid(value.ToString()));
                }

                return (T)Convert.ChangeType(value, type);
            }
            catch (Exception) 
            {
                return default(T);
            }
        } 
    }
}
